package test.designmode.delegatecomm;

/**
 * 该类主要用于具体实现所有slot并将其进行注册
 */
public class ProtocolBase implements FrameSentReceivedEventHandler {

    private CommPortBase commPort = null;

    public ProtocolBase(CommPortBase commPort) {
        this.commPort = commPort;
        regEvnToPort();
    }

    /**
     * @brief 模拟触发事件, 类似于emit msg_signal(msg)
     * @param msg
     */
    public void onMessageComming(String msg) {
        commPort.callEventMessageOccured(this, msg);
    }

    public void onFrameSend(String frame) {
        commPort.callEventFrameSend(this, frame);
    }

    public void onFrameRec(String frame) {
        commPort.callEventFrameRec(this, frame);
    }
    
    public void onFrameJava8(String frame) {
        commPort.callEventFrameJava8(this, frame);
    }

    /**
     * @brief SLOT:该方法和MessageOccuredEventHandler.dnInvokeDelegate有耦合关系
     * @param sender
     * @param msg
     */
    public void printMessage(Object sender, String msg) {
        System.out.println("现在打印信息:" + msg);
        System.out.println("----------消息来自对象:" + sender.toString());
    }

    /**
     * @brief SLOT:该方法和MessageOccuredEventHandler.dnInvokeDelegate有耦合关系
     * @param sender
     * @param msg
     */
    public void reSendMessage(Object sender, String msg) {
        System.out.println("现在回发信息:" + msg);
        System.out.println("----------消息来自对象:" + sender.toString());
    }

    /**
     * @brief 给port注册事件处理
     */
    private void regEvnToPort() {
        // 为新port注册事件, 一个EventHandler代表一个事件, ProtocolBase有EventHandler的ArrayList
        MessageOccuredEventHandler evMsgOccur1 = new MessageOccuredEventHandler(this, "printMessage");
        commPort.addMessageOccuredEventListener(evMsgOccur1);
        MessageOccuredEventHandler evMsgOccur2 = new MessageOccuredEventHandler(this, "reSendMessage");
        commPort.addMessageOccuredEventListener(evMsgOccur2);

        // 上面是反射法, 这个是普通的接口法
        commPort.addFrame4Java8EventHandler((sender, sentframe)->{System.out.println("Java8 is good");}); //Java8 Lambda
    }

    @Override
    public void onStringSentEvent(Object sender, String sentframe) {
        System.out.println("已发送的数据帧为:" + sentframe);
    }

    @Override
    public void onStringReceivedEvent(Object sender, String recframe) {
        System.out.println("已接收的数据帧为:" + recframe);
    }

}
